import {createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw, useRoute} from 'vue-router'
import App from "@/App.vue";
import useUserStore from "@/store/modules/user";
import {getQueryObject} from "@/utils/index";
import StorageUtils from "@/utils/StorageUtils";
import NurseApp from "@/views/nurse/NurseClient.vue";
import LoginView from "@/views/nurse/LoginView.vue";
import NurseHome from "@/views/nurse/NurseHome.vue";

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Nurse',
    component: App,
    redirect: {name: 'NurseClient'},
    children: [
      {
        path: 'login',
        name: 'NurseLogin',
        component: LoginView,
      }, {
        path: 'client',
        name: 'NurseClient',
        component: NurseApp,
        redirect: {name: 'NurseHome'},
        beforeEnter: (to, from,next) => {
          // 当前登录用户信息
          const userStore = useUserStore()
          if (!userStore.id) {
            Promise.all([userStore.getInfo()]).then(() => {
              next()
            })
          } else {
            next()
          }
        },
        children: [
          {
            path: 'home',
            name: 'NurseHome',
            component: NurseHome,
          },
          {
            path: 'profile',
            component: () => import('@/views/system/user/profile/index.vue'),
            name: 'NurseProfile',
            meta: { title: '个人中心', icon: 'user' }
          }
        ]
      }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  const params = getQueryObject()
  if (params?.token) {
    StorageUtils.setUserLoginTokenStorage(params.token as string)
  }
  const token = StorageUtils.getUserLoginToken();
  console.log('------------token-------------', token)
  if (to.name != 'NurseLogin' && !token) {
    next({ name: 'NurseLogin' })
  }
  else next();
})

export default router
